package models

import play.api.Logger
import play.api.db.slick.Config.driver.simple._
import scala.slick.lifted.ForeignKeyAction

case class Resource(id: Option[Long] = None, name: String, 
  version: Option[String] = None, uri: String, groupId: Long)

object ResourceTbl extends Table[Resource]("RES_REF") {

  def id = column[Long]("id", O.PrimaryKey, O.AutoInc)
  def name = column[String]("name", O.NotNull)
  def version = column[String]("version", O.Nullable)
  def uri = column[String]("uri", O.NotNull)
  def groupId = column[Long]("grp_id", O.NotNull)
  def groupFk = foreignKey("grp_id_fk", groupId, GroupTbl)(_.id, onDelete = ForeignKeyAction.Cascade)
  def uniqueName = index("idx_res_name_version", (name, version), unique = true)

  def * = id.? ~ name ~ version.? ~ uri ~ groupId <> (Resource.apply _, Resource.unapply _)

  def autoInc = * returning id

  val byId = createFinderBy(_.id)
}

object ResourceDAO {
  /**
  * Retrieve a resource from the id
  * @param id
  */
  def findById(id: Long)(implicit s: Session): Option[Resource] =
  ResourceTbl.byId(id).firstOption

  /**
  * Count all resources
  */
  def count(implicit s: Session): Int =
  Query(ResourceTbl.length).first

  /**
   * Insert a new resource
   * @param group
   */
  def insert(resource: Resource)(implicit s: Session) {
    ResourceTbl.autoInc.insert(resource)
  }

  /**
   * Update a resource
   * @param resource
   */
  def update(resource: Resource)(implicit s: Session) {
    val resourceToUpdate: Resource = resource.copy(resource.id)
    ResourceTbl.where(_.id === resource.id).update(resourceToUpdate)
  }

  /**
   * Delete a resource
   * @param id
   */
  def delete(id: Long)(implicit s: Session) {
    ResourceTbl.where(_.id === id).delete
  }

}